import { BASEURL } from '@/apis/http'
import { driveRoad } from './driveRoad'
import { uploadImgByIdAPI } from '@/apis'
import { ElMessage } from 'element-plus'

// 获取经纬度坐标
function getPoints(address, cb) {
  const myGeo = new BMap.Geocoder()
  // 将地址解析结果显示在地图上，并调整地图视野
  myGeo.getPoint(
    address,
    (point) => {
      if (point) {
        cb(point)
      }
    },
    '北京市'
  )
}

// marker绑定事件
function addMarkerEvent({
  map,
  marker,
  label,
  point,
  mark,
  lat,
  lng,
  titleArr,
}) {
  // 给marker添加特定id表示
  const dealArr = titleArr.map((item) => {
    return {
      prop: item.prop,
      name: item.name,
      value: mark[item.prop] === null ? '无' : mark[item.prop],
    }
  })
  const strJson = dealArr
    .map((item) => {
      //  return `<li  style="line-height:40px;" >${item.name}: ${item.value}</li>`
      if (item.prop === 'images') {
        return `
        <li style="line-height:40px;">
          <div>现场图片:${item.value == '无' ? '无现场图片' : ''}</div>
          <div style="height:auto;">
          ${
            item.value == '无'
              ? ''
              : `<div style="height:0;position:relative;padding-top:75%;"><img src='${BASEURL}/${item.value}' style="position:absolute;top:0;left:0;width:100%;height:100%;"/></div>`
          }
          </div>
        </li>
      `
      } else if (item.prop === 'typeName') {
        return `<li style="line-height:40px; color:#FFD04B; font-weight:700;" >
          <div> ${item.name}: ${item.value} </div>
        </li>`
      } else {
        return `<li style="line-height:40px;" >
         <div> ${item.name}: ${item.value} </div>
        </li>`
      }
    })
    .join('')

  marker.id = mark.id
  const reactHeight = mark.images ? 720 : 600
  const opts = {
    title: `
      点位信息 <button id="driveTo">导航过去</button>
      <input type="file" id="upload"/>
    `,
    width: 800,
    height: reactHeight,
    overflow: 'auto',
  }
  const infoWindow = new BMap.InfoWindow(
    `
      <ul style="max-height:${reactHeight}px; padding-bottom: 120px; overflow: auto;">
       ${strJson}
      </ul>
    `,
    opts
  )

  function openInfoWindow() {
    map.openInfoWindow(infoWindow, point)

    document.getElementById('driveTo').addEventListener('click', () => {
      // 点击规划导航路线
      driveRoad(map, lat, lng, mark.pointName)
    })
    document
      .getElementById('upload')
      .addEventListener('change', async (res) => {
        const file = res.target.files[0]
        const fd = new FormData()
        fd.append('file', file)
        await uploadImgByIdAPI(mark.id, fd)
        ElMessage({
          type: 'success',
          message: '上传图片成功',
        })
        // 更新显示
        marker.clickEvent()
      })
  }

  // 浏览器原生事件 由用户点击触发
  marker.addEventListener('click', () => {
    openInfoWindow()
  })

  label.addEventListener('click', () => {
    openInfoWindow()
  })

  // 自定义事件 由JS脚本触发
  marker.clickEvent = () => {
    openInfoWindow()
  }
}

// 添加Marker

function getBgColor(typeId, typeList) {
  const targetType = typeList.find((type) => type.id === typeId)
  if (targetType) {
    return targetType.color
  } else {
    return ''
  }
}

function addMarker(map, markList, needColor) {
  const titleArr = JSON.parse(needColor.contents)

  // 清除上一次Marker类别
  map.getOverlays().forEach((item) => {
    if (item.pR === 'Marker') {
      map.removeOverlay(item)
    }
  })

  markList.forEach((mark) => {
    const [lng, lat] = mark.longLatitude.split(',')
    const point = new BMap.Point(lng, lat)
    const marker = new BMap.Marker(point)
    const labelopts = {
      points: point,
      offset: new BMap.Size(20, -15),
    }
    const label = new BMap.Label(mark.pointName, labelopts)
    label.setStyle({
      color: '#fff',
      fontSize: '14px', // 字体大小
      borderColor: '#ccc', // 边框颜色
      borderWidth: 1, // 边框宽度
      borderRadius: '4px', // 边框圆角
      backgroundColor: getBgColor(mark.typeId, needColor.children),
      padding: '5px', // 内边距
      lineHeight: '20px', // 行高
    })
    marker.setLabel(label)
    map.addOverlay(marker)
    addMarkerEvent({ map, marker, label, point, mark, lat, lng, titleArr })

    // getPoints(`${mark.pointName}`, (points) => {
    //   const { lat, lng } = points
    //   const point = new BMap.Point(lng, lat)
    //   const marker = new BMap.Marker(point)
    //   const labelopts = {
    //     points: point,
    //     offset: new BMap.Size(20, -15),
    //   }
    //   const label = new BMap.Label(mark.pointName, labelopts)
    //   label.setStyle({
    //     color: '#fff',
    //     fontSize: '14px', // 字体大小
    //     borderColor: '#ccc', // 边框颜色
    //     borderWidth: 1, // 边框宽度
    //     borderRadius: '4px', // 边框圆角
    //     backgroundColor: getBgColor(mark.typeId, needColor.children),
    //     padding: '5px', // 内边距
    //     lineHeight: '20px', // 行高
    //   })
    //   marker.setLabel(label)
    //   map.addOverlay(marker)

    //   addMarkerEvent({ map, marker, label, point, mark, lat, lng, titleArr })
    // })
  })
}

export { addMarker }
